<?php

namespace app\wechat\controller;

use Pheanstalk\Pheanstalk;
use think\Db;

class Task
{
    public $pheanstalk;

    public function __construct()
    {
        $this->pheanstalk = new Pheanstalk('127.0.0.1');
    }

    // 整体状态
    public function stats()
    {
        return $this->pheanstalk->stats();
    }

    // 管道状态
    public function statsTube()
    {
        $res = $this->pheanstalk->statsTube('customer');
        return json($res) ? json($res) : '';
    }

    // Job状态
    public function statsJob($id)
    {
        $job = $this->pheanstalk->peek($id);
        $res = $this->pheanstalk->statsJob($job);
        return $res ? $res : '';
    }

    // 删除某个定时任务
    public function deleteJob($id)
    {
        $job = $this->pheanstalk->peek($id);
        $this->pheanstalk->delete($job);
        return $this->pheanstalk->statsTube('customer');
    }

    // 获取所有定时任务
    public function query()
    {
        $tasks = Db::table('task')->select();

        $list = array();
        foreach ($tasks as $task) {
            if ($task['delay'] > time()) {
                $acc = Db::table('authorizers')->where('appid', $task['acc_id'])->find();
                $task['acc_id'] = $acc['name'];
                array_push($list, $task);
            }
        }

        return json($list);
    }

    // 删除定时任务
    public function delete($job_id)
    {
        $_tube = $this->pheanstalk->statsTube('customer');
        $_delay_num = $_tube['current-jobs-delayed'];
        $tube = $this->deleteJob($job_id);
        $delay_num = $tube['current-jobs-delayed'];
        if ($_delay_num - $delay_num == 1) {
            $res = Db::table('task')->where('job_id', $job_id)->delete();
            if ($res == 1) {
                return 'ok';
            } else {
                return 'error';
            }
        } else {
            return 'error';
        }
    }
}
